//
//  ChatBaseCell.m
//  学生汇
//
//  Created by yull on 14/11/12.
//  Copyright (c) 2014年 于博. All rights reserved.
//

#import "ChatBaseCell.h"
#import "UIImageView+WebCache.h"
#import "FunctionMethod.h"

@implementation ChatBaseCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        
        CGRect rect = CGRectMake(0, 15, 45, 45);
        self.headImageView = [[UIImageView alloc] initWithFrame:rect];
        self.headImageView.layer.cornerRadius = CGRectGetWidth(rect) / 2;
        self.headImageView.layer.masksToBounds = YES;
        self.headImageView.userInteractionEnabled = YES;
        [self.contentView addSubview:self.headImageView];
        
        rect = CGRectMake(0, 15, 20, CGRectGetHeight(self.contentView.frame)-35);
        self.contentImageView = [[UIImageView alloc] initWithFrame:rect];
        self.contentImageView.backgroundColor = [UIColor clearColor];
        self.contentImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        self.contentImageView.userInteractionEnabled = YES;
        [self.contentView addSubview:self.contentImageView];
        
        rect = CGRectMake(0, self.contentView.height - 20, self.contentView.width, 20);
        self.timeLabel = [[UILabel alloc] initWithFrame:rect];
        self.timeLabel.backgroundColor = [UIColor clearColor];
        self.timeLabel.font = [UIFont systemFontOfSize:14.0f];
        self.timeLabel.textColor = RGB(137, 137, 137);
        self.timeLabel.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [self.contentView addSubview:self.timeLabel];
        
        self.chatContentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 1, 1)];
        self.chatContentView.backgroundColor = [UIColor clearColor];
        [self.contentImageView addSubview:self.chatContentView];
        
        rect = CGRectMake(0, 0, 23, 23);
        self.failImageView = [[UIImageView alloc] initWithFrame:rect];
        self.failImageView.image = [UIImage imageNamed:@"chat_send_fail"];
        self.failImageView.centerY = CGRectGetHeight(self.contentView.frame)/2;
        self.failImageView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
        self.failImageView.userInteractionEnabled = YES;
        [self.contentView addSubview:self.failImageView];
        
        self.failImageView.hidden = YES;
        
//        rect = CGRectMake(0, 0, 25, 12);
//        self.sendingImageView = [[UIImageView alloc] initWithFrame:rect];
//        self.sendingImageView.animationImages = [NSArray arrayWithObjects:[UIImage imageNamed:@"chat_sending_1"],[UIImage imageNamed:@"chat_sending_2"],[UIImage imageNamed:@"chat_sending_3"], nil];
//        self.sendingImageView.animationDuration = 0.5f;
//        self.sendingImageView.centerY = CGRectGetHeight(self.contentView.frame)/2;
//        self.sendingImageView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
//        [self.contentView addSubview:self.sendingImageView];
//        self.sendingImageView.hidden = YES;
        
        self.sendingIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        self.sendingIndicatorView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
        [self.contentView addSubview:self.sendingIndicatorView];
        
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapGesture:)];
        [self.contentImageView addGestureRecognizer:tapGesture];
        
        UITapGestureRecognizer *headTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onHeadTapGesture:)];
        [self.headImageView addGestureRecognizer:headTapGesture];
        
        UITapGestureRecognizer *failGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapGesture:)];
        [self.failImageView addGestureRecognizer:failGesture];
    }
    return self;
}

- (void)drawCellWithChatMsg:(ChatBaseMsg *)chatMsg
{    
    [self removeMessageObserver];
    
    self.chatMsg = chatMsg;
    
    [self addMessageObserver];
    
    if (chatMsg.roleType == ChatMsgRoleTypeReceive) {
        
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:chatMsg.icon] placeholderImage:[UIImage imageNamed:@"zc_photo_bg"]];
        
        self.chatContentView.left = self.xSpace + CHAT_CELL_DELTA;
        self.chatContentView.top = self.ySpace;
        
        self.headImageView.left = CHAT_CELL_LEFT_SPACE;
        
        self.contentImageView.width = self.chatContentView.width + 2 * self.xSpace;
        self.contentImageView.left = self.headImageView.right + 5;
        
        self.timeLabel.left = self.contentImageView.left + 5;
        self.timeLabel.width = self.contentView.width - self.timeLabel.left;
        self.timeLabel.textAlignment = NSTextAlignmentLeft;
        
        UIImage *image = [UIImage imageNamed:@"chat_left_bg"];
        self.contentImageView.image = [image stretchableImageWithLeftCapWidth:15 topCapHeight:image.size.height - 5];
    
        self.sendingIndicatorView.left = self.contentImageView.right + 2;
        self.sendingIndicatorView.bottom = self.contentImageView.bottom - 2;
    }else {
        
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:[CurrentUser shareInstance].icon] placeholderImage:[UIImage imageNamed:@"zc_photo_bg"]];
        
        self.chatContentView.left = self.xSpace - CHAT_CELL_DELTA;
        self.chatContentView.top = self.ySpace;
        
        self.headImageView.right = self.contentView.width - CHAT_CELL_LEFT_SPACE;
        
        self.contentImageView.width = self.chatContentView.width + 2 * self.xSpace;
        self.contentImageView.right = self.headImageView.left - 5;
        
        self.timeLabel.left = 0;
        self.timeLabel.width = self.contentImageView.right - 5;
        self.timeLabel.textAlignment = NSTextAlignmentRight;
        
        UIImage *image = [UIImage imageNamed:@"chat_right_bg"];
        self.contentImageView.image = [image stretchableImageWithLeftCapWidth:10 topCapHeight:image.size.height-5];
        
        self.sendingIndicatorView.right = self.contentImageView.left - 2;
        self.sendingIndicatorView.bottom = self.contentImageView.bottom - 2;
    }
    
    self.timeLabel.text = [FunctionMethod getChatTimeTextWithTimeStamp:chatMsg.createTime];
    
    if (chatMsg.sendStatus == ChatMsgSendStatusSending) {
        [self showSendingImageView];
    }else {
        [self hideSendingImageView];
    }
    
    if (chatMsg.sendStatus == ChatMsgSendStatusFail) {
        self.failImageView.hidden = NO;
    }else {
        self.failImageView.hidden = YES;
    }
}

- (void)showSendingImageView
{
    self.sendingIndicatorView.hidden = NO;
    
    [self.sendingIndicatorView startAnimating];
}

- (void)hideSendingImageView
{
    self.sendingIndicatorView.hidden = YES;
    [self.sendingIndicatorView stopAnimating];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

}

- (void)onTapGesture:(UITapGestureRecognizer *)tapGesture
{
    if (self.chatMsg.sendStatus == ChatMsgSendStatusFail) {
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"重新发送" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"重新发送" otherButtonTitles: nil];
        [actionSheet showInView:self];
    }else {
        //if ([self.delegate respondsToSelector:@selector(onContentSingleTap)]) {
            //[self.delegate onContentSingleTap];
        //}
    }
}

- (void)onHeadTapGesture:(UITapGestureRecognizer *)tapGesture
{
    if ([self.delegate respondsToSelector:@selector(onHeadClickWithMessage:)]) {
        [self.delegate onHeadClickWithMessage:self.chatMsg];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0 && [self.delegate respondsToSelector:@selector(onResend:)]) {
        [self.delegate onResend:self.chatMsg];
    }
}

- (void)addMessageObserver
{
    [self.chatMsg addObserver:self forKeyPath:@"sendStatus" options:NSKeyValueObservingOptionNew context:nil];
 
    [self.chatMsg addObserver:self forKeyPath:@"audioRestTime" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.chatMsg addObserver:self forKeyPath:@"audioStatus" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.chatMsg addObserver:self forKeyPath:@"isRead" options:NSKeyValueObservingOptionNew context:nil];
    
    [self.chatMsg addObserver:self forKeyPath:@"picUploadPercent" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeMessageObserver
{
    [self.chatMsg removeObserver:self forKeyPath:@"sendStatus"];
    
    [self.chatMsg removeObserver:self forKeyPath:@"audioRestTime"];
    
    [self.chatMsg removeObserver:self forKeyPath:@"audioStatus"];
    
    [self.chatMsg removeObserver:self forKeyPath:@"isRead"];
    
    [self.chatMsg removeObserver:self forKeyPath:@"picUploadPercent"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{

    if ([keyPath isEqualToString:@"sendStatus"]) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (self.chatMsg.sendStatus == ChatMsgSendStatusSending) {
                [self showSendingImageView];
            }else {
                [self hideSendingImageView];
            }
            
            if (self.chatMsg.sendStatus == ChatMsgSendStatusFail) {
                self.failImageView.hidden = NO;
            }else {
                self.failImageView.hidden = YES;
            }
            
            if (self.chatMsg.sendStatus == ChatMsgSendStatusSuccess) {
                [self hideSendingImageView];
                self.failImageView.hidden = YES;
            }
        });
    }
}
- (void)dealloc
{
    [self removeMessageObserver];
}
@end
